﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace DataOperation
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string source = textBox1.Text.Trim();
            string target = textBox2.Text.Trim();
            string name = textBox3.Text.Trim();
            string location = textBox4.Text.Trim();
            string num = textBox5.Text.Trim();
            string fileName = name + "_" + location;
            if (string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(target) || ((string.IsNullOrWhiteSpace(name) ||
                string.IsNullOrWhiteSpace(location)) && string.IsNullOrWhiteSpace(num)))
            {
                MessageBox.Show("信息不完整，无法操作，请填入必填项。", "提示信息",
    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (target[target.Length - 1] != '\\')
            {
                target = target + "\\";
            }
            if (source[source.Length - 1] != '\\')
            {
                source = source + "\\";
            }
            string fileLocation = string.Empty;
            if (string.IsNullOrWhiteSpace(num))
            {
                fileLocation = target + fileName + ".xlsx";
            }
            else
            {
                fileLocation = target + num + ".xlsx";
            }
            string[] fileEntries = Directory.GetFiles(source);
            Dictionary<DateTime, string[,]> result = new Dictionary<DateTime, string[,]>();
            try
            {
                foreach (var info in fileEntries)
                {
                    foreach (string item in File.ReadAllLines(info))
                    {
                        string[] cols = item.Split(',');
                        string[,] resultTemp = new string[48, 5];
                        if (cols[0].Trim().Equals(num) || (name.Equals(cols[6].Trim(), StringComparison.InvariantCultureIgnoreCase) &&
                      location.Equals(cols[7].Trim(), StringComparison.InvariantCultureIgnoreCase)))
                        {
                            int year = int.Parse(cols[1]);
                            int month = int.Parse(cols[2]);
                            int day = int.Parse(cols[3]);
                            int hour = int.Parse(cols[4]);
                            DateTime dt = new DateTime(year, month, day, hour, 0, 0);

                            for (int i = 0; i < 48; i++)
                            {
                                int add = i * 3;
                                resultTemp[i, 0] = i.ToString();
                                resultTemp[i, 1] = dt.AddHours(-47 + i).ToLongDateString() + " " + dt.AddHours(-47 + i).ToLongTimeString();
                                resultTemp[i, 2] = cols[158 - add];
                                resultTemp[i, 3] = cols[159 - add];
                                resultTemp[i, 4] = cols[160 - add];
                            }
                            result.Add(dt, resultTemp);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("处理源文件时出错,出错原因:" + err.Message, "提示信息",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            try
            {
                result.OrderBy(o => o.Key);
                DataTable table = MakeTable();
                foreach (var item in result)
                {
                    string[,] value = item.Value;
                    for (var i = 0; i < 48; i++)
                    {
                        DataRow row;
                        row = table.NewRow();
                        row["id"] = value[i, 0];
                        row["Date"] = value[i, 1];
                        row["SO2"] = value[i, 2];
                        row["NO2"] = value[i, 3];
                        row["PM10"] = value[i, 4];

                        table.Rows.Add(row);
                    }
                }
                ExcelOperation.SaveDataTableToExcel(table, fileLocation);
                label10.Text = num + name + location + "  Success!";
            }
            catch (Exception err)
            {
                MessageBox.Show("写入文件时出错,出错原因:" + err.Message, "提示信息",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private DataTable MakeTable()
        {
            // Create a new DataTable.
            System.Data.DataTable table = new DataTable("Table");
            // Declare variables for DataColumn and DataRow objects.
            DataColumn column;

            // Create new DataColumn, set DataType, 
            // ColumnName and add to DataTable.    
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "id";
            column.ReadOnly = false;
            column.Unique = false;
            // Add the Column to the DataColumnCollection.
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "Date";
            column.AutoIncrement = false;
            column.Caption = "Date";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "SO2";
            column.AutoIncrement = false;
            column.Caption = "SO2";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "NO2";
            column.AutoIncrement = false;
            column.Caption = "NO2";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "PM10";
            column.AutoIncrement = false;
            column.Caption = "PM10";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);

            //// Make the ID column the primary key column.
            //DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            //PrimaryKeyColumns[0] = table.Columns["id"];
            //table.PrimaryKey = PrimaryKeyColumns;

            return table;
        }

        private void button2_Click(object sender, EventArgs e)
        {

            textBox1.Text = showFolderSelect();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox2.Text = showFolderSelect();
        }

        private string showFolderSelect()
        {
            folderBrowserDialog1.ShowNewFolderButton = true;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                return folderBrowserDialog1.SelectedPath;
            }
            else
            {
                return string.Empty;
            }
        }


    }
}
